﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using WPFDBBrowser.Helpers;
using WPFDBBrowser.MessageBus;

namespace WPFDBBrowser.Framework
{
    public class PresenterBase<TView>
    {
        IEndPoint _endpoint;

        public PresenterBase()
            : this(null)
        {
        }

        public PresenterBase(string instanceName)
        {
            this.InstanceName = instanceName;
            this._endpoint = this.MessageBus.RegisterEndpoint(this.GetIdentification()).Start();
        }

        protected virtual string GetIdentification()
        {
            return this.GetType().FullName;
        }

        protected TView View { get; private set; }

        public string InstanceName { get; set; }

        protected IUnityContainer UnityContainer
        {
            get
            {
                //return UnityResolver.GetContainer();
                return UnityContainerFactory.GetInstance();
            }
        }
        /// <summary>
        /// Returns Service provider.
        /// </summary>
        protected IServiceProvider ServiceProvider
        {
            get
            {
                return this.UnityContainer.Resolve<IServiceProvider>();
            }
        }

        protected IMessageBus MessageBus
        {
            get
            {
                return this.UnityContainer.Resolve<IMessageBus>();
            }
        }

        public virtual void SetView(object view)
        {
            if (!(view is TView))
                throw new InvalidCastException(
                    string.Format("Can't cast view to {0}.", typeof(TView).FullName));
            if (view == null)
                throw new NullReferenceException("view");
            this.View = (TView)view;
        }

        public virtual void OnViewLoaded()
        {
        }
        public virtual void OnViewClosed()
        {
        }

        protected void PublishMessage<TMessage>(TMessage message)
        {
            this._endpoint.Publish<TMessage>(message);
        }
    }
}
